import React, { useEffect, useState } from 'react';
import { connect } from 'umi';
import { Card, Descriptions, Typography, Row, Col, Space, Tag, Collapse, Button, Modal } from 'antd'
import PopImgShow from '@/components/PopImgShow';
import TableDataBlock from '@/components/TableDataBlock';
import CheckOrderForm from './components/CheckOrderForm';
import ImagePreviewGroup from '@/components/DescriptionsCondition/ImagePreviewGroup';
import ToRechargeOrderForm from './components/ToRechargeOrderForm';
import CardComponents from './components/CardComponents'
import CommissionTable from './components/commissionTable'
import CommissionItemSnap from './components/commissionItemSnap'
import CancelOrder from './components/CancelOrder';
import StagePerformance from './components/StagePerformance';
import ModelForm from './../OrderList/components/ModelForm'
import ChangePayRecord from './components/changePayRecord'
import ChangeEnter from './components/changeEnter';
import ExpressDetail from './components/ExpressDetail'
import InvalidOrderModal from './../OrderList/components/CancelOrder'
import './index.less'
import { order_status, ExpressStatus, goodsType_status, operation_statusinfo, workType_status, pay_type } from '@/common/contact';
const { Title, Text } = Typography;
const { Panel } = Collapse;
const OrderDetails = (props) => {
  const { history, dispatch, loading } = props;
  const { location = {} } = history
  const { query = {} } = location
  const { orderSn = '', linkType = 'user', id, setType = 'user' } = query
  const [data, setData] = useState({})
  const [checkVisible, setCheckVisible] = useState(false)
  const [cancelOrder, setCancelOrder] = useState(false)
  const [toRechargeOrderVisible, setToRechargeOrderVisible] = useState(false)
  const [invalidOrderVisible, setInvalidOrderVisible] = useState(false)
  const [modelFormVisible, setModelFormVisible] = useState(false)
  const [changePayRecordVisible, setChangePayRecordVisible] = useState(false)
  const [changeEnterVisible, setChangeEnterVisible] = useState(false)
  const fetchData = () => {
    dispatch({
      type: 'order/fetchOrderDetail',
      payload: {
        orderSn: orderSn,
      },
      callback: (record) => {
        setData(record)
      }
    });
  }
  useEffect(() => {
    fetchData()
  }, [])
  const
    DescriptionsRender = (props) => {
      const { title, value = {}, formItems = [] } = props
      return <Descriptions {...props} title={<Title level={4}>{title}</Title>}>
        {formItems.map((item, index) => {
          const { label, name, render } = item
          if (render) {
            return <Descriptions.Item labelStyle={{ fontSize: 14 }} contentStyle={{ fontSize: 14 }} key={index} label={<Text level={3}>{label}</Text>}>{render(value[name], value)}</Descriptions.Item>
          }
          return <Descriptions.Item labelStyle={{ fontSize: 14 }} contentStyle={{ fontSize: 14 }} key={index} label={<Text level={3}>{label}</Text>}>{value[name] ? value[name] : '--'}</Descriptions.Item>
        })}
      </Descriptions>
    }
  const { orderInfo = {}, detailOrderPayRecordList = [], goodsInfo = {} } = data
  const { operationStatus, status, remainFlag, nowCheckRechargeMoney, afterSaleStatus, invalidFlag, stageInfo = {} } = orderInfo
  const { stageName } = stageInfo
  const userFormItem = [{
    label: '姓名',
    name: 'username'
  }, {
    label: '手机',
    name: 'mobile'
  },]
  const shopFormItem = [{
    label: '商品信息',
    name: 'orderDesc',
    render: (e) => {
      const goods = e ? JSON.parse(e) : {}
      const { goodsCover, goodsName } = goods
      return <Space>
        <div>{goodsName}</div>
      </Space>
    }
  }, {
    label: '商品数量',
    name: 'goodsAmount',
    render: (e) => {
      if (!e) {
        return '--'
      }
      return e
    },
  },
  {
    label: '商品售价',
    name: 'totalFee',
    render: (e) => {
      if (!e) {
        return '--'
      }
      return e
    },
  },
  {
    label: '商品底价',
    name: 'goodsMinPrice',
    render: (e) => {
      if (!e) {
        return '--'
      }
      return e
    },
  },]
  const OrderFormItem = [
    {
      label: '订单编号',
      name: 'orderSn',
    },
    {
      label: '订单类型',
      name: 'orderType',
      render: (e) => {
        if (!e) {
          return '--'
        }
        return goodsType_status[e]
      },
    },


    {
      label: '状态',
      name: 'status',
      render: (e) => {
        return order_status[e]
      },
    },
    {
      label: '阶段',
      name: 'userStage',
      render: (e) => {
        if (!stageName) {
          return '--'
        }
        return stageName
      }
    },
    {
      label: '服务类型',
      name: 'workType',
      render: (e) => {
        if (!e) {
          return '--'
        }
        return workType_status[e]
      }
    },
    {
      label: '物流状态 ',
      name: 'expressStatus',
      render: (e) => {
        if (!e) {
          return '--'
        }
        return ExpressStatus[e]
      }
    },
  ]
  const payFormItem = [
    {
      label: '应收',
      name: 'payFee',
    },
    {
      label: '实收',
      name: 'realPayFee',
    },
    {
      label: '欠费',
      name: 'remainMoney',
      render: (e) => {
        return <div style={{ color: 'red' }}>{e}</div>
      }
    },

    {
      label: '超额优惠',
      name: 'additionalDiscounts',
      render: (e) => {
        return <div style={{ color: 'red' }}>{e}</div>
      }
    },
    {
      label: '支付时间',
      name: 'payTime',
    },
    {
      label: '开单时间',
      name: 'orderDate',
    },
    {
      label: '复核人',
      name: 'checkAdminName',
    },
    {
      label: '复核时间',
      name: 'checkTime',
    },

    {
      label: '复核状态',
      name: 'operationStatus',
      render: (e) => {
        return operation_statusinfo[e]
      }
    },
    {
      label: '收据编号',
      name: 'receiptNo',
    },

    {
      label: '订单备注',
      name: 'remark',
    },
    {
      label: '审核备注',
      name: 'checkRemark',
    },
    {
      label: '收据图片',
      name: 'certificateImages',
      render: (e) => {
        return <ImagePreviewGroup url={e}></ImagePreviewGroup>
      }
    },
  ].filter(item => {
    const { show = true } = item
    return show
  })
  const bfTitle = (data = {}) => {
    if (data) {
      const { orderRechargeFlag } = data
      if (orderRechargeFlag === '1' || orderRechargeFlag === '3') {
        return '当前审核补费'
      }
      return '当前审核付款'
    }
    return '当前审核付款'

  }
  const bfForm = [
    {
      label: '欠费总金额',
      name: 'remainMoney',
      show: remainFlag === '1'
    },
    {
      label: bfTitle(detailOrderPayRecordList[0]),
      name: 'nowCheckRechargeMoney',
      show: remainFlag === '1' && Number(nowCheckRechargeMoney) > 0
    },
    {
      label: '剩余待补费',
      name: 'remainMoney',
      show: remainFlag === '1'
    },
  ].filter(item => {
    const { show = true } = item
    return show
  })
  const checkedFormItem = [
    {
      label: '创建人',
      name: 'addAdminName',
    },
  ]
  const getColumns = [
    // {
    //   title: '订单编号',
    //   dataIndex: 'orderSn',
    // },
    {
      title: '支付金额',
      dataIndex: 'payFee',
    },
    {
      title: '支付时间',
      dataIndex: 'payTime',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (e) => {
        return operation_statusinfo[e]
      }
    },
    {
      title: '支付方式',
      dataIndex: 'payType',
      render: (e) => {
        return pay_type[e]
      }
    },
    {
      title: '凭证图片',
      dataIndex: 'certificateImages',
      render: (e) => {
        return <ImagePreviewGroup width={40} height={40} url={e}></ImagePreviewGroup>
      }
    },
    {
      title: '是否补费',
      dataIndex: 'orderRechargeFlag',
      render: (e) => {
        if (e === '1') {
          return <Tag style={{ textAlign: 'center' }} color="#f50">是</Tag>
        } else if (e === '2') {
          return <Tag style={{ textAlign: 'center' }} color="#87d068">否</Tag>
        }
        else if (e === '3') {
          return '售后补费'
        }
        else return '--'
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '用户姓名',
      dataIndex: 'username',
    },
    {
      title: '头像',
      dataIndex: 'profile',
      render: (e) => {
        return <PopImgShow url={e}></PopImgShow>
      }
    },
    {
      title: '手机',
      dataIndex: 'mobile',
    },
    {
      title: '创建员工',
      dataIndex: 'addAdminName',
    },
    {
      title: '审核员工',
      dataIndex: 'checkAdminName',
    },
    {
      title: '审核时间',
      dataIndex: 'checkTime',
    },
  ];
  if (linkType === 'checkOrder') {
    return (
      <Card
        loading={loading}
        style={{ paddingBottom: '60px' }}
        title='复核订单'
      >
        <Collapse ghost bordered={false} defaultActiveKey={['1', '2', '3', '4', '5']}>
          <Panel header={<Title level={4}>学生信息</Title>} key="1">
            <DescriptionsRender column={5} formItems={userFormItem} value={orderInfo}></DescriptionsRender>
          </Panel>
          <Panel header={<Title level={4}>商品信息</Title>} key="2">
            <DescriptionsRender border column={6} formItems={shopFormItem} value={orderInfo}></DescriptionsRender>
          </Panel>
          <Panel header={<Title level={4}>订单信息</Title>} key="3">
            <DescriptionsRender border column={3} formItems={OrderFormItem} value={orderInfo}></DescriptionsRender>
          </Panel>
          <Panel header={<Title level={4}>支付信息</Title>} key="4">
            <DescriptionsRender border column={3} formItems={bfForm} value={orderInfo}></DescriptionsRender>
            <TableDataBlock
              cardProps={
                { title: '支付信息列表' }
              }
              // searchItems={searchItems}
              columns={getColumns}
              list={detailOrderPayRecordList}
              rowKey={(record) => `${record.id}`}
            ></TableDataBlock>
            <DescriptionsRender border column={3} formItems={payFormItem} value={orderInfo}></DescriptionsRender>
          </Panel>
          <Panel header={<Title level={4}>经办人</Title>} key="5">
            <DescriptionsRender border column={1} formItems={checkedFormItem} value={orderInfo}></DescriptionsRender>
          </Panel>

        </Collapse>
        <ExpressDetail detail={orderInfo}></ExpressDetail>
        <CheckOrderForm visible={checkVisible} onClose={() => setCheckVisible(false)}></CheckOrderForm>
        <div className='handle_btn_info'>
          <Button type='primary' onClick={() => setCheckVisible({
            show: true,

            detail: {
              ...orderInfo,
              payTime: detailOrderPayRecordList[0].payTime,
              payFee: detailOrderPayRecordList[0].payFee,
              certificateImages: detailOrderPayRecordList[0].certificateImages
            }
          })} >审核</Button>
        </div>
      </Card>
    );
  } else if (linkType === 'ToRecharge') {
    const { rechargeId } = query
    return (
      <Card
        loading={loading}
        title='复核补费'
        style={{ paddingBottom: '60px' }}
      >
        <Collapse ghost bordered={false} defaultActiveKey={['1', '2', '3', '4', '5']}>
          <Panel header={<Title level={4}>学生信息</Title>} key="1">
            <DescriptionsRender column={5} formItems={userFormItem} value={orderInfo}></DescriptionsRender>
          </Panel>
          <Panel header={<Title level={4}>商品信息</Title>} key="2">
            <DescriptionsRender border column={6} formItems={shopFormItem} value={orderInfo}></DescriptionsRender>
          </Panel>
          <Panel header={<Title level={4}>订单信息</Title>} key="3">
            <DescriptionsRender border column={3} formItems={OrderFormItem} value={orderInfo}></DescriptionsRender>
          </Panel>
          <Panel header={<Title level={4}>支付信息</Title>} key="4">
            <DescriptionsRender border column={3} formItems={bfForm} value={orderInfo}></DescriptionsRender>
            <TableDataBlock
              cardProps={
                { title: '支付信息列表' }
              }
              // searchItems={searchItems}
              columns={getColumns}
              list={detailOrderPayRecordList}
              rowKey={(record) => `${record.id}`}
            ></TableDataBlock>
            <DescriptionsRender border column={3} formItems={payFormItem} value={orderInfo}></DescriptionsRender>
          </Panel>
          <Panel header={<Title level={4}>经办人</Title>} key="5">
            <DescriptionsRender border column={1} formItems={checkedFormItem} value={orderInfo}></DescriptionsRender>
          </Panel>

        </Collapse>
        <ExpressDetail detail={orderInfo}></ExpressDetail>
        <ToRechargeOrderForm visible={toRechargeOrderVisible} onClose={() => setToRechargeOrderVisible(false)}></ToRechargeOrderForm>
        <div className='handle_btn_info'>
          <Button onClick={() => setToRechargeOrderVisible({
            show: true,
            detail: {
              ...orderInfo,
              payTime: detailOrderPayRecordList[0].payTime,
              payFee: detailOrderPayRecordList[0].payFee,
              certificateImages: detailOrderPayRecordList[0].certificateImages,
              id: rechargeId
            }
          })} type='primary'>审核</Button>
        </div>
      </Card >
    );

  } else {
    const { orderStatus, } = query
    const { commissionOrderInfo = {}, commissionItemList = [], commissionItemSnapshotList = [], stageAdminCommissionList = [] } = data
    const { commissionWay = 'stage', orderSn } = commissionOrderInfo
    const commissionItems = [
      {
        label: '确认日期',
        name: 'confirmTime',
      },
      {
        label: '分佣金额',
        name: 'commissionFee',
      },
      {
        label: '扣除佣金',
        name: 'deductCommission',
      },
    ];
    const renderButton = () => {
      if (invalidFlag === '1' && operationStatus === '2') {
        return <div className='handle_btn_info'>
          <Button onClick={() => {
            setInvalidOrderVisible({ show: true, detail: orderInfo, type: 'cance' })
          }} type='primary'>恢复订单</Button>
        </div>
      }
      else if (status !== '2' && afterSaleStatus !== '0' && (operationStatus === '1' || operationStatus === '3')) {
        return <div className='handle_btn_info'>
          <Button onClick={() => {
            dispatch({
              type: 'order/fakeCheckInvalidCheckOrder',
              payload: {
                orderSn: orderSn
              },
              callback: (e) => {
                const {
                  alertFlag,
                  alertMessage,
                  mustFlag
                } = e
                if (alertFlag === '1') {
                  if (mustFlag === '1') {
                    Modal.error({
                      title: '警告提示',
                      content: alertMessage,
                    });
                  }
                  else {
                    Modal.confirm({
                      title: '提示',
                      content: alertMessage,
                      okText: '继续作废',
                      onOk() {
                        setInvalidOrderVisible({ show: true, detail: orderInfo })
                      },
                      onCancel() {
                        console.log('Cancel');
                      },
                    })
                  }
                }
                else {
                  setInvalidOrderVisible({ show: true, detail: orderInfo })
                }
              }
            })
          }} type='primary'>作废</Button>
        </div>
      }
      return null
    }
    return <Card
      loading={loading}
      style={{ paddingBottom: '60px' }}
      title={'订单详情'}
    >
      <Collapse ghost bordered={false} defaultActiveKey={['1', '2', '3', '4', '5', '6', '7', '8', '9']}>
        <Panel header={<Title level={4}>学生信息</Title>} key="1">
          <DescriptionsRender column={5} formItems={userFormItem} value={orderInfo}></DescriptionsRender>
        </Panel>
        {goodsInfo.id ? <Panel header={<Title level={4}>商品信息</Title>} key="2">
          <DescriptionsRender border column={6} formItems={shopFormItem} value={orderInfo}></DescriptionsRender>
        </Panel> : null}
        <Panel header={<Title level={4}>订单信息</Title>} key="3">
          <DescriptionsRender border column={3} formItems={OrderFormItem} value={orderInfo}></DescriptionsRender>
        </Panel>
        <Panel header={<Title level={4}>支付信息</Title>} key="4">
          <DescriptionsRender border column={3} formItems={bfForm} value={orderInfo}></DescriptionsRender>
          <TableDataBlock
            cardProps={
              { title: '支付信息列表' }
            }
            // searchItems={searchItems}
            columns={getColumns}
            list={detailOrderPayRecordList}
            rowKey={(record) => `${record.id}`}
          ></TableDataBlock>
          <DescriptionsRender border column={3} formItems={payFormItem} value={orderInfo}></DescriptionsRender>
        </Panel>

        <Panel header={<Title level={4}>经办人</Title>} key="5">
          <DescriptionsRender border column={1} formItems={checkedFormItem} value={orderInfo}></DescriptionsRender>
        </Panel>
      </Collapse>
      {renderButton()}
      <InvalidOrderModal handleCallback={fetchData} visible={invalidOrderVisible} onClose={() => setInvalidOrderVisible(false)}></InvalidOrderModal>
      <ExpressDetail detail={orderInfo}></ExpressDetail>
      <ChangePayRecord handleCallback={fetchData} visible={changePayRecordVisible} onClose={() => setChangePayRecordVisible(false)}></ChangePayRecord>
      <ChangeEnter handleCallback={fetchData} visible={changeEnterVisible} onClose={() => setChangeEnterVisible(false)}></ChangeEnter>
    </Card>
  }

};
export default connect(({ loading }) => ({
  loading: loading.effects['order/fetchOrderDetail'],
}))(OrderDetails);
